package com.sunmouse.toolkit.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunmouse.toollib.adapter.BasicAdapter;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.constant.Media;
import com.sunmouse.toolkit.ftp.FileBean;


import java.util.List;


/**
 * Created by Administrator on 2017/8/23.
 */
public class FileAdapter extends BasicAdapter<FileAdapter.ViewHolder, FileBean> {


    public FileAdapter(List<FileBean> list, Context context) {
        super(list, context);
    }

    @Override
    protected View bindView(LayoutInflater inflater, ViewGroup parent, Context context, List<FileBean> list, int position) {
        return inflater.inflate(R.layout.adapter_file, parent, false);
    }

    @Override
    protected ViewHolder bindViewHolder(View cv, ViewGroup parent, Context context) {
        return new ViewHolder(cv);
    }

    @Override
    protected void bindData(ViewHolder vh, int position, List<FileBean> list, Context context) {
        FileBean f = list.get(position);
        vh.iconIv.setImageResource(selectedIcon(f));
        vh.nameTv.setText(f.getName());
        vh.sizeTv.setText(selectedUnit(f));
    }

    /**
     * selected unit
     *
     * @param f
     * @return
     */
    private String selectedUnit(FileBean f) {
        String out;
        long size = f.getSize();
        if (size >= 1024 * 1024) {
            out = String.valueOf(f.getSize() / (1024 * 1024)) + "M";
        } else if (size > 1024) {
            out = String.valueOf(f.getSize() / 1024) + "kb";
        } else {
            out = String.valueOf(f.getSize()) + "b";
        }
        return out;
    }

    static class ViewHolder extends BasicAdapter.ViewHolder {
        ImageView iconIv;
        TextView nameTv;
        TextView sizeTv;

        public ViewHolder(View v) {
            super(v);
            this.iconIv = (ImageView) v.findViewById(R.id.icon_iv);
            this.nameTv = (TextView) v.findViewById(R.id.title_tv);
            this.sizeTv = (TextView) v.findViewById(R.id.size_tv);
        }
    }

    /**
     * select file icon
     *
     * @param f
     * @return
     */
    private int selectedIcon(FileBean f) {
        if (f.getFileType() == 1) {
            return R.mipmap.format_folder;
        } else {
            String name = f.getName();
            if (Media.isRadio(name)) {
                return R.mipmap.format_music;
            } else if (Media.isVideo(name)) {
                return R.mipmap.format_media;
            } else if (Media.isCompress(name)) {
                return R.mipmap.format_zip;
            } else if (Media.isDoc(name)) {
                return R.mipmap.format_text;
            } else {
                return R.mipmap.format_unkown;

            }
        }
    }
}
